package com.miniapp.oauth2;

import com.miniapp.entity.MiniUserEntity;
import com.miniapp.entity.MiniUserTokenEntity;
import com.miniapp.entity.enums.UserStatus;
import com.miniapp.service.MiniUserService;
import com.miniapp.service.ShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 认证
 *
 * @author linyuchi
 * @email xunli-03@163.com
 * @date 2017-05-20 14:00
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;
    @Autowired
    private MiniUserService miniUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        MiniUserTokenEntity tokenEntity = shiroService.queryByToken(accessToken);
        //token失效
        // TODO: 2018/4/17 先去掉token失效 
//        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
        if(tokenEntity == null ){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
       MiniUserEntity user = miniUserService.getById(tokenEntity.getUserId());
        //账号锁定
        if(user.getStatus().equals(UserStatus.UNACTIVE)){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
